package com.huaxinkaiye.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.NetworkImageView;
import com.google.gson.Gson;
import com.huaxinkaiye.R;
import com.huaxinkaiye.application.HuaXinApplication;
import com.huaxinkaiye.bean.ListBean;
import com.huaxinkaiye.bean.PictureInfo;
import com.huaxinkaiye.lookbigphoto.PhotosDialog;
import com.huaxinkaiye.utils.FileImageUpload;
import com.huaxinkaiye.utils.ImageUtils;
import com.huaxinkaiye.utils.OptionsUtil;
import com.huaxinkaiye.utils.PhotoImplActivity;
import com.huaxinkaiye.utils.MySharedPreferences;
import com.huaxinkaiye.utils.ProgressUtil;
import com.huaxinkaiye.utils.SimpleClient;
import com.huaxinkaiye.utils.ToastUtil;
import com.huaxinkaiye.utils.UrlUtils;
import com.huaxinkaiye.utils.analysisCar;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class JianDangActivity2 extends PhotoImplActivity implements
		OnClickListener, OnLongClickListener {
	private ImageView im_queren, im_home;
	private ImageView im_photo;
	private TextView te_photo;
	private EditText te_chepaihao, te_beizhu;
	TextView te_chepaiyanse, te_cheshenyanse;
	Spinner spinner, cs_spinner;
	public List<NameValuePair> params;
	public ProgressUtil progress;
	public JSONArray jsonarray0, jsonarray1;
	public List<Map<String, Object>> data, data2;
	public Map<String, Object> map;
	public int cheshenid, chepaiid;
	public JSONArray array;
	public ListBean listbean;
	public String picUrldata;
	public int carid = 0;
	public String localPicPath = "";
	public String localBigPicPath = "";
	public String carID;
	public String s_chepaiyanse, s_cheshenyanse;
	private static final int TIME_OUT = 5;
	private static final int SUCCESS = 1;
	// 超时的时限为50秒
	private static final int TIME_LIMIT = 30000;
	Timer timer;
	Thread thread;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				JiexiData0(msg.obj.toString());
				break;
			case 1:
				JiexiData(msg.obj.toString());
				break;
			case 3:
				progress.dismiss();
				jiexipictureData(msg.obj.toString());
				break;
			case 4:
				jiexichepai(msg.obj.toString());
				break;
			case TIME_OUT:
				// 打断线程
				thread.interrupt();
				ToastUtil.show(JianDangActivity2.this, "网路超时");
				progress.dismiss();
				//ToastUtil.show(JianDangActivity2.this, "");
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jiandang);
		initView();
	}

	protected void jiexichepai(String s) {
		// TODO Auto-generated method stub
		Log.e("jiexipicture_data", s);
		try {
			if (s.equals("{}")) {
				ToastUtil.show(this, "图片不够标准");
			}
			JSONObject json = new JSONObject(s);
			if (json.getBoolean("result")) {
				te_chepaihao.setText(json.getString("code").replace("\u0000",""));
				ToastUtil.show(this, json.getString("message"));
			} else {
				ToastUtil.show(this, json.getString("message"));
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		progress.dismiss();
	}

	protected void jiexipictureData(String string) {
		// TODO Auto-generated method stub
		Log.e("picture_data", string);
		try {
			JSONObject json = new JSONObject(string);
			Gson gson = new Gson();
			PictureInfo pr = gson.fromJson(string, PictureInfo.class);
			if (pr.getIsSuccess().equals("true")) {
				for (int i = 0; i < pr.getPictureInfo().size(); i++) {
					if (pr.getPictureInfo().get(i).getFileType() == 1) {
						localBigPicPath = UrlUtils.host
								+ pr.getPictureInfo().get(i).getPath();
					}
				}
				Log.e("localBigPicPath==", localBigPicPath);
				ImageLoader.getInstance().displayImage(localBigPicPath,
						im_photo, OptionsUtil.optionsAvatar);
				ToastUtil.show(this, pr.getMessage());
			} else {
				ToastUtil.show(this, pr.getMessage());
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		im_queren = (ImageView) findViewById(R.id.im_queren);
		im_queren.setOnClickListener(this);
		im_home = (ImageView) findViewById(R.id.im_home);
		im_home.setOnClickListener(this);
		im_photo = (ImageView) findViewById(R.id.im_photo);
		im_photo.setOnClickListener(this);
		im_photo.setOnLongClickListener(this);
		te_photo = (TextView) findViewById(R.id.te_photo);
		te_photo.setOnClickListener(this);
		te_chepaihao = (EditText) findViewById(R.id.te_chepaihao);
		// te_chepaiyanse = (TextView) findViewById(R.id.te_chepaiyanse);
		// te_cheshenyanse = (TextView) findViewById(R.id.te_cheshenyanse);
		te_beizhu = (EditText) findViewById(R.id.te_beizhu);
		spinner = (Spinner) findViewById(R.id.lq_spinner);
		cs_spinner = (Spinner) findViewById(R.id.cs_spinner);
		InitchepaiSpinnerData();
		InitcheshenSpinnerData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		InitcheshenSpinnerData();
		InitchepaiSpinnerData();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_home:
			im_photo.setImageResource(R.drawable.xiangji);
			localPicPath = "";
			localBigPicPath = "";
			te_chepaihao.setText("");
			te_beizhu.setText("");
			break;
		case R.id.im_queren:
			uploadphoto();
			break;
		case R.id.im_photo:
			// 查看大图
			if (localBigPicPath.equals("")) {
				ToastUtil.show(this, "车牌照片没有上传");
				return;
			}
			lookBigImage();
			break;
		case R.id.te_photo:
			jiexiphoto();
			break;
		}
	}

	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_photo:
			showPopupMenu(im_photo, true, "jiandang");
			break;
		}
		return true;
	}

	@Override
	public void doAfterZoom(Bitmap bitmap) {
		// TODO Auto-generated method stub
		im_photo.setImageBitmap(ImageUtils.createFramedPhoto(bitmap));
		localPicPath = ImageUtils
				.savePicToCache(JianDangActivity2.this, bitmap);
		Log.e("localPicPath1", localPicPath);
	}

	private void uploadphoto() {
		// TODO Auto-generated method stub
		if (localPicPath.equals("")) {
			ToastUtil.show(this, "请上传车牌照片");
			return;
		}
		if (te_chepaihao.getText().toString().equals("")) {
			ToastUtil.show(this, "车牌号不为空");
			return;
		}
		// if (te_chepaiyanse.getText().toString().equals("")) {
		// ToastUtil.show(this, "车牌颜色不为空");
		// return;
		// }
		// if (te_cheshenyanse.getText().toString().equals("")) {
		// ToastUtil.show(this, "车身颜色不为空");
		// return;
		// }
		// if (te_chepaiyanse.getText().toString()
		// .equals(te_cheshenyanse.getText().toString())) {
		// ToastUtil.show(this, "车身车牌颜色不能相同");
		// return;
		// }
		for (int i = 0; i < jsonarray0.length(); i++) {
			JSONObject json;
			try {
				json = new JSONObject(jsonarray0.get(i).toString());
				if (json.getString("name").equals(s_cheshenyanse)) {
					cheshenid = json.getInt("id");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for (int i = 0; i < data2.size(); i++) {
			JSONObject json;
			try {
				json = new JSONObject(jsonarray1.get(i).toString());
				if (json.getString("name").equals(s_chepaiyanse)) {
					chepaiid = json.getInt("id");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("plateNumber", te_chepaihao.getText()
				.toString()));
		params.add(new BasicNameValuePair("carBodyColorId", cheshenid + ""));
		params.add(new BasicNameValuePair("plateColorId", chepaiid + ""));
		params.add(new BasicNameValuePair("filingMemo", te_beizhu.getText()
				.toString()));
		params.add(new BasicNameValuePair("pictureFile", localPicPath));
		final String url = UrlUtils.jiandang_url2;
		if (HuaXinApplication.isNetWorkConnected()) {
			progress = new ProgressUtil(this, "正在上传数据");
			progress.show();
			thread = new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					Log.e("localPicPath", localPicPath);
					String result = FileImageUpload.postFile(url, params);
					Message message = new Message();
					message.what = 3;
					message.obj = result;
					handler.sendMessage(message);
				}
			};
			thread.start();
			// 设定定时器
			timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					sendTimeOutMsg();
				}
			}, TIME_LIMIT);
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}

	protected void lookBigImage() {
		// TODO Auto-generated method stub
		final ArrayList<String> urllist = new ArrayList<String>();
		urllist.add(localBigPicPath);
		new PhotosDialog(JianDangActivity2.this, R.style.Dialog).show(0,
				urllist);
	}

	private void jiexiphoto() {
		// TODO Auto-generated method stub
		if (localPicPath.equals("")) {
			ToastUtil.show(this, "请上传图片");
			return;
		}
		progress = new ProgressUtil(this, "正在解析车牌号");
		progress.show();
		thread = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String result = analysisCar.main(localPicPath);
				Log.e("result_jiexichepai", result);
				Message message = new Message();
				message.what = 4;
				message.obj = result;
				handler.sendMessage(message);
			}
		};
		thread.start();
		 //设定定时器
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				sendTimeOutMsg();
			}
		}, TIME_LIMIT);
	}

	private void InitcheshenSpinnerData() {
		// TODO Auto-generated method stub
		String url = UrlUtils.chepaiyanshe + "parentId=1";
		Log.e("cheshenyanse_url", url);
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("parentId", "1"));
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient.doPost(UrlUtils.chepaiyanshe, params);
					MySharedPreferences.getInstance(JianDangActivity2.this)
							.setString("cheshenyanse", data);
					Log.e("cheshenyanse", data);
					Message message = new Message();
					message.what = 0;
					message.obj = data;
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void InitchepaiSpinnerData() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			String url = UrlUtils.chepaiyanshe + "parentId=2";
			Log.e("chepaiyanse_url", url);
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("parentId", "2"));
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					String data;
					try {
						data = SimpleClient.doPost(UrlUtils.chepaiyanshe,
								params);
						MySharedPreferences.getInstance(JianDangActivity2.this)
								.setString("chepaiyanse", data);
						Log.e("chepaiyanse", data);
						Message message = new Message();
						message.what = 1;
						message.obj = data;
						handler.sendMessage(message);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			JiexiData(MySharedPreferences.getInstance(this).getString(
					"chepaiyanse"));
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}

	protected void JiexiData0(String cheshenyanse) {
		// TODO Auto-generated method stub
		data2 = new ArrayList<Map<String, Object>>();
		Log.e("cheshenyanse---", cheshenyanse);
		try {
			jsonarray0 = new JSONArray(cheshenyanse);
			for (int i = 0; i < jsonarray0.length(); i++) {
				JSONObject json = new JSONObject(jsonarray0.get(i).toString());
				map = new HashMap<String, Object>();
				map.put("text", json.get("name").toString());
				data2.add(map);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, data2,
				R.layout.spinner, new String[] { "text" },
				new int[] { R.id.textView1 });
		// simpleAdapter.
		// 设置显示的数据
		cs_spinner.setAdapter(simpleAdapter);
		// 注册事件
		cs_spinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						Toast.makeText(getApplicationContext(), "没有改变的处理",
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Spinner spinner = (Spinner) arg0;
						s_cheshenyanse = spinner
								.getItemAtPosition(arg2)
								.toString()
								.substring(
										6,
										spinner.getItemAtPosition(arg2)
												.toString().length() - 1)
								+ "";
						// te_cheshenyanse.setText(spinner
						// .getItemAtPosition(arg2)
						// .toString()
						// .substring(
						// 6,
						// spinner.getItemAtPosition(arg2)
						// .toString().length() - 1)
						// + "");
					}
				});
	}

	protected void JiexiData(String chepaiyanse) {
		// TODO Auto-generated method stub
		data = new ArrayList<Map<String, Object>>();
		Log.e("chepaiyanse---", chepaiyanse);
		try {
			jsonarray1 = new JSONArray(chepaiyanse);
			for (int i = 0; i < jsonarray1.length(); i++) {
				JSONObject json = new JSONObject(jsonarray1.get(i).toString());
				map = new HashMap<String, Object>();
				map.put("text", json.get("name").toString());
				data.add(map);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, data,
				R.layout.spinner, new String[] { "text" },
				new int[] { R.id.textView1 });
		// 设置显示的数据
		spinner.setAdapter(simpleAdapter);
		// 注册事件
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				Toast.makeText(getApplicationContext(), "没有改变的处理",
						Toast.LENGTH_LONG).show();
			}

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				Spinner spinner = (Spinner) arg0;
				s_chepaiyanse = spinner
						.getItemAtPosition(arg2)
						.toString()
						.substring(
								6,
								spinner.getItemAtPosition(arg2).toString()
										.length() - 1)
						+ "";
				// te_chepaiyanse.setText(spinner
				// .getItemAtPosition(arg2)
				// .toString()
				// .substring(
				// 6,
				// spinner.getItemAtPosition(arg2).toString()
				// .length() - 1)
				// + "");
			}
		});
	}

	// 向handler发送超时信息
	private void sendTimeOutMsg() {
		Message timeOutMsg = new Message();
		timeOutMsg.what = TIME_OUT;
		handler.sendMessage(timeOutMsg);
	}
}
